package cn.com.startai.smartadh5.main.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import cn.com.startai.smartadh5.R;
import cn.com.startai.smartadh5.extension.utils.LogUtil;
import cn.com.startai.smartadh5.locallog.SmartLocalLog;
import cn.com.startai.smartadh5.locallog.entity.LogMsg;

/**
 * 跑马灯效果
 * 只有文字，暂时不能加 padding
 *
 */
public class MarqueeView extends SurfaceView implements SurfaceHolder.Callback {

    private SurfaceHolder holder;
    private RefreshThread myThread;
    private boolean threadIsStart;

    protected TextPaint mTextPaint;
    protected float textSize = 100; //时间数字的字体大小
    protected int textColor = Color.BLACK; //时间数字的颜色
    private String marqueeString;
    private int textWidth = 0;//文字大小
    private int baseLineOffset = 0;//文字基线，相对于绘制的中间线的偏移量
    private int mWidth = 0;//该控件的宽度
    private int mHeight = 0;//该控件的高度
    protected int textBackgroundColor = Color.WHITE;

    private int sepX = 100;//x的间隔

    public MarqueeView(Context context) {
        super(context);
        init(null, 0);
    }

    public MarqueeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public MarqueeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs, defStyleAttr);
    }

    public void init(AttributeSet attrs, int defStyle) {
        this.setZOrderOnTop(true);
        this.getHolder().setFormat(PixelFormat.TRANSPARENT);

        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.marquee, defStyle, 0);
        textColor = a.getColor(
                R.styleable.marquee_textcolor,
                Color.BLACK);
        textSize = a.getDimension(
                R.styleable.marquee_textSize,
                24);
        a.recycle();
        holder = this.getHolder();
        holder.addCallback(this);
        mTextPaint = new TextPaint();
        mTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);//抗锯齿
        mTextPaint.setTextAlign(Paint.Align.LEFT);

    }

    public void setText(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            measurementsText(msg);
        }
    }

    public void setTextColor(String color) {
        if (color != null) {
            textColor = Color.parseColor(color);
        }
    }

    public void setTextBackgroundColor(String backgroundColor) {
        if (backgroundColor != null) {
            textBackgroundColor = Color.parseColor(backgroundColor);
        }
    }

    public void setTextSize(int textSize) {
        if (textSize > 0) {
            this.textSize = textSize;
            mTextPaint.setTextSize(textSize);
            postInvalidate();
        }
    }

    public void setSpeed(int speed) {
        this.sepX = speed;
    }

    protected void measurementsText(String msg) {
        marqueeString = msg;
        mTextPaint.setTextSize(textSize);
        mTextPaint.setColor(textColor);
        mTextPaint.setFakeBoldText(true);
        // 设定阴影(柔边, X 轴位移, Y 轴位移, 阴影颜色)
//        mTextPaint.setShadowLayer(5, 3, 3, ShadowColor);
        textWidth = (int) mTextPaint.measureText(marqueeString);
        Paint.FontMetricsInt fontMetrics = mTextPaint.getFontMetricsInt();
        baseLineOffset = (fontMetrics.bottom - fontMetrics.top) / 2 + fontMetrics.top;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        mWidth = width;
        mHeight = height;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        //创建一个绘图线程
        myThread = new RefreshThread(holder);
        myThread.isRun = true;
        if (!threadIsStart) {
            myThread.start();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        myThread.isRun = false;
        LogUtil.e("live"," surfaceDestroyed ");
    }


    //线程内部类
    private class RefreshThread extends Thread {
        long t = 0;
        private SurfaceHolder holder;
        boolean isRun;
        int currentX;


        RefreshThread(SurfaceHolder holder) {
            this.holder = holder;
            isRun = true;
            currentX = mWidth;
        }


        void onDraw() {
            synchronized (holder) {
                Canvas mCanvas = null;

                t = System.currentTimeMillis();
                try {

                    if (TextUtils.isEmpty(marqueeString)) {
                        Thread.sleep(1000);
                        return;
                    }

                    mCanvas = holder.lockCanvas();
//                    mCanvas.save();
//                    mCanvas.translate(1,0);


//                    if(sepX == 0) {
//                        currentX = 0;
//                    } else {
                    if (currentX <= -textWidth) {
                        currentX = mWidth;
                    } else {
                        currentX -= sepX;
                    }
//                    }

                    if(mCanvas !=null){

                        mCanvas.drawColor(textBackgroundColor);
                        mCanvas.drawText(marqueeString, currentX, mHeight / 2 - baseLineOffset, mTextPaint);

                    }

                    // 线程休眠 再次更新
                    int sleepTime = 16;
                    Thread.sleep(Math.max(0, sleepTime - (System.currentTimeMillis() - t)));

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 结束锁定画图，并提交改变。
                    if(mCanvas !=null){
                        try {
                            if(isRun=true){
                                holder.unlockCanvasAndPost(mCanvas);
//                                mCanvas.restore();
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            LogUtil.e("live"," exception " ,e);
                            SmartLocalLog.writeLog(new LogMsg(LogMsg.TYPE_HANDLER, "ADH5", "异常", e.getMessage()));
                        }
                    }

                }
            }

        }

        @Override
        public void run() {
            threadIsStart = true;
            while (isRun) {
                onDraw();

            }
        }

    }

}